import json
from copy import deepcopy
from flask import Blueprint, request, jsonify
from controllers.common import *
from controllers.db import *

growth_ladder_api = Blueprint('growth_ladder_api', __name__)
growth_ladder_down_api = Blueprint('growth_ladder_down_api', __name__)


@growth_ladder_api.route('/growth_ladder', methods=['POST'])
def growth_ladder():
    params = json.loads(request.data)
    _action = params['action']
    _project = params['project']
    result_data = {'status': 200, 'data': {'msg': '', 'ret': 0, 'type': 'success', 'env': EVN, 'item': ''}}
    if _action == 'detail':
        query = GrowthLadder.query.filter_by(project=_project).first()
        tmp = {
            "project": int(query.project),
            'basic': json.loads(query.basic),
            'detail': json.loads(query.detail)
        }
        result_data['data']['item'] = tmp
    elif _action == 'update_part':
        _data = params['data']
        _part = params['part']
        '''growth_ladder_data = GrowthLadder.query.filter_by(project=_project).first()
        reward = json.loads(growth_ladder_data.reward)'''
        if _part == 'basic':
            GrowthLadder.query.filter_by(project=_project).update({
                'basic': json.dumps(_data)
            })
        elif _part == 'detail':
            GrowthLadder.query.filter_by(project=_project).update({
                'detail': json.dumps(_data)
            })
        db.session.commit()
        result_data['data']['msg'] = "更新成功"
    elif _action == 'iap_list':
        with open(STATIC_PATH + 'iap_list.json') as f:
            data = json.load(f)
            for i in data:
                i['value'] = i['gem']
                i['label'] = i['label'] + ' - ' + str(i['gem'])
            return json.dumps(data)
    elif _action == 'get_doc_id_list':
        return jsonify(get_doc_id_list_in_operation_event_english('growth_ladder_event', 'title'))
    return jsonify(result_data)


@growth_ladder_down_api.route('/growth_ladder_down/<int:is_push>', methods=['GET', 'POST'])
def growth_ladder_down(is_push):
    growth_ladder_event_project = {}

    query = GrowthLadder.query.order_by('project').all()

    for q in query:
        _project = str(q.project)
        basic = json.loads(q.basic)
        detail = json.loads(q.detail)

        purchase_list = []
        level = 0
        for i in detail['gift']:
            purchase_list.append({
                'reward': RewardToTMysqlNew(i['reward']),
                'level': level,
                'basic_gems': i['basic_gems'],
                'project_id': int(f"1127{_project.zfill(4)}{str(i['id']).zfill(4)}"),
                'scoring_rules': [1, 1, 1, 0]
            })
            level += 1

        growth_ladder_event_project[_project] = {
            'basic_data': {
                'event_ui': basic['event_ui']
            },
            'doc_id': basic['doc_id'],
            'free_reward': RewardToTMysqlNew(basic['free_reward']),
            'purchase_list': purchase_list
        }

    if is_push == 0:
        response = DownLoad('growth_ladder_event_project', growth_ladder_event_project, 0)
    else:
        response = DownLoad('growth_ladder_event_project', growth_ladder_event_project, 1)
    return response
